package com.changgou.seckill.consumer;

import com.alibaba.fastjson.JSON;
import com.changgou.pay.feign.WeixinPayFeign;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.service.SeckillOrderService;
import entity.Result;
import entity.SeckillStatus;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: hushengjin
 */

@Component
@RabbitListener(queues = "${mq.pay.queue.seckillordertimer}")
public class SeckillOrderDelayMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WeixinPayFeign weixinPayFeign;
    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 读取消息
     * 判断Redis中是否存在对应的订单
     * 如果存在，则关闭支付，再关闭订单
     *
     * @param msg
     */
    @RabbitHandler
    public void consumerMessage(@Payload String msg) {
        //读取消息
        SeckillStatus seckillStatus = JSON.parseObject(msg, SeckillStatus.class);
        //获取redis中的订单的数据
        String username = seckillStatus.getUsername();
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder").get(username);
        //如果redis中有订单,说明用户未支付
        if (seckillOrder != null) {
            //关闭订单
            Result result = weixinPayFeign.closePay(seckillStatus.getOrderId());
            Map<String, String> closeMap = (Map<String, String>) result.getData();
            if (closeMap != null && closeMap.get("return_code").equalsIgnoreCase("success") && closeMap.get("result_code").equalsIgnoreCase("success")) {
                //关闭订单 回滚订单
                seckillOrderService.closeOrder(username);
            }
        }
    }

}
